<?php

namespace App\Jobs\Cruise\SelfCheck;

use App\Models\Cruise\CruiseCheckSelfDetailModel;
use App\Models\Cruise\CruiseOrderModel;
use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

/**
 * 门店自检任务 到期自动过期
 */
class TaskExpiredJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * job 描述
     *
     * @var string
     */
    public string $description = "门店自检任务 到期自动过期";

    /**
     * cruise_check_self_detail.id
     *
     * @var int
     */
    public int $id;

    /**
     * 延迟时间
     *
     * @var int
     */
    public int $delayTime;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(int $id, int $delayTime)
    {
        $this->id        = $id;
        $this->delayTime = $delayTime;
    }

    /**
     * Execute the job.
     *
     * @return void
     * @throws Exception
     */
    public function handle()
    {
        Log::info($this->description, [
            "className" => self::class,
            "params"    => ["id" => $this->id]
        ]);

        try {
            $cruiseCheckSelfDetailModel = CruiseCheckSelfDetailModel::query()
                                                                    ->where("id", $this->id)
                                                                    ->first();

            if ($cruiseCheckSelfDetailModel && $cruiseCheckSelfDetailModel->status == CruiseCheckSelfDetailModel::STATUS_1) {
                if ($cruiseCheckSelfDetailModel->executeEndTime <= time()) {
                    // 当前任务 为待完成 & 执行结束时间小于当前时间 -》 变更为已过期
                    CruiseCheckSelfDetailModel::query()
                                              ->where("id", $this->id)
                                              ->update([
                                                  "status"    => CruiseCheckSelfDetailModel::STATUS_3,
                                                  "updatedAt" => time()
                                              ]);

                    // 更新状态为已过期
                    CruiseOrderModel::query()->where("id", $cruiseCheckSelfDetailModel->cruiseOrderId)->update([
                        "status" => CruiseOrderModel::STATUS_EXPIRED
                    ]);
                }
            }
        } catch (Exception $exception) {
            logException($this->description, $exception, ["id" => $this->id]);
        }
    }

    /**
     * 过期
     *
     * @throws Exception
     */
    public function expiredDispatch()
    {
        if ($this->delayTime > 0) {
            // 未过期触发延时任务
            dispatch($this)->delay($this->delayTime);
        } else {
            // 已过期直接触发
            $this->handle();
        }
    }
}
